/* $RCSFile: CrmBSM2.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.EMailing/PageModules/CRMEMailing/CrmBSM2.ascx.cs $
 * $log$
 * Revision 53 2010/10/02 18:54:31  christian.surieux
 *   Update ADNDyn* pour PrimaryFieldStingValue et update telerik
 * Revision 31 2010/10/01 11:24:58  christian.surieux
 *   Fixing temporary version on 1/10/2010
 * Revision 23 2010/08/09 11:12:45  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 10 2010/08/09 10:13:18  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;
using System.Text;
using System.Threading;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Authentication;
using AddonNice.Core;

using AddonNice.CRMWrapper;
using AddonNice.CRMEMailing;
using AddonNice.CRMEMailing.Settings.UI.WebControls;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using AddonNice.CRMWrapper.CRMEMailing;

namespace AddonNice.PageModules.CRMEMailing
{

    /// <summary>
    /// Initializer class for CrmBSM2 
    /// </summary>
    public class CrmBSM2SI : PortalCRMModuleControlSI
    {
        public CrmBSM2SI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( CrmBulkSendTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2SI Ctor BEG.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmBulkSendTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( CrmBulkSendTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2SI Ctor END.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmBulkSendTrace.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2SI InitSettings BEG.",CrmBulkSendTrace.Sw.Info);
            
            base.InitSettings(bSettings,pm);

			// Specific parameters
            const string extgrp                 =   "CRMBULKSEND";
            
            SettingItemSpecial FixedCampaign    =   new SettingItemSpecial(AStr.FixedCampaign,new BooleanDataType());
            FixedCampaign.Required              =   false;
            FixedCampaign.ResourceFile          =   AStr.ResourceFile;
            FixedCampaign.ResourceItem          =   AStr.ResourceItem;
            FixedCampaign.Value                 =   StStr.strFalse;
            FixedCampaign.Order                 =   10;
            FixedCampaign.ExtendedGroupName     =   extgrp;
            FixedCampaign.EnglishName           =   "Fixed Campaign";
            FixedCampaign.Description           =   "When checked, module will use the campain selected in next setting";
            bSettings.AddSetting(FixedCampaign);

            //Fixed campaign
            WSListDataType defCampaign          =   new WSListDataType(CrmStr.campaign,"name", "ID");
            SettingItemSpecial Campaign         =   new SettingItemSpecial(AStr.BulkCampaign,defCampaign);
            Campaign.EnglishName                =   "Campaign";
            Campaign.Order                      =   20;
            Campaign.ResourceFile               =   AStr.ResourceFile;
            Campaign.ResourceItem               =   AStr.ResourceItem;
            Campaign.ExtendedGroupName          =   extgrp;
            Campaign.Description                =   "Select a default campaign to associate with this Rating";
            Campaign.SettingItemsEvent          +=  new SettingItemsEventHandler(Campaign_SettingItemsEvent);
            bSettings.AddSetting(Campaign);

            SettingItemSpecial Assign2Owner     =   new SettingItemSpecial(AStr.Assign2Owner,new BooleanDataType());
            Assign2Owner.Required               =   false;
            Assign2Owner.ResourceFile           =   AStr.ResourceFile;
            Assign2Owner.ResourceItem           =   AStr.ResourceItem;
            Assign2Owner.Value                  =   StStr.strFalse;
            Assign2Owner.Order                  =   30;
            Assign2Owner.ExtendedGroupName      =   extgrp;
            Assign2Owner.EnglishName            =   "Assign to Owner";
            Assign2Owner.Description            =   "When checked, the new crm contact will be automatically assigned to selected owner";
            bSettings.AddSetting(Assign2Owner);

            WSListDataType defAcc               =   new WSListDataType(CrmStr.systemuser,"name", "ID");
            SettingItemSpecial ModuleOwner      =   new SettingItemSpecial(AStr.TemplateOwner,defAcc);
            // default == CRMDefaultAccount or first
            ADNDynSystemUser wsys                =   null;
            if (!string.IsNullOrEmpty(Config.CRMDefaultAccount))
            {
                string domainName               =   string.Format("{0}\\{1}",Config.CRMDefaultAccountDomain,Config.CRMDefaultAccount);
                wsys                            =   Wrapper.Util.FindSystemUserByDomainName(domainName);
            }
            else 
            {
                wsys                            =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,ResetWrapper,Wrapper.adminUserId);
            }
            if (wsys != null)
            {
                ModuleOwner.Value               =   wsys.systemuserid.ToString();
                defAcc.DisplayTextValue         =   wsys.fullname;
            }
            ModuleOwner.Order                   =   40;
            ModuleOwner.ExtendedGroupName       =   extgrp;
            ModuleOwner.ResourceFile            =   AStr.ResourceFile;
            ModuleOwner.ResourceItem            =   AStr.ResourceItem;
            ModuleOwner.EnglishName             =   "Owner";
            ModuleOwner.Description             =   "Set a default owner for templates created with this module";
            ModuleOwner.SettingItemsEvent       +=  new SettingItemsEventHandler(ModuleOwner_SettingItemsEvent);
            bSettings.AddSetting(ModuleOwner);
            
            SettingItemSpecial TargetDomain     =   new SettingItemSpecial(AStr.TargetDomain,new StringDataType());
            TargetDomain.Required               =   true;
            TargetDomain.ResourceFile           =   AStr.ResourceFile;
            TargetDomain.ResourceItem           =   AStr.ResourceItem;
            TargetDomain.Value                  =   string.Format("www.{0}.com",portalSettings.PortalAlias);
            TargetDomain.Order                  =   42;
            TargetDomain.ExtendedGroupName      =   extgrp;
            TargetDomain.EnglishName            =   "Default target domain";
            TargetDomain.Description            =   "Target domain for 'More info link', including extension (.com, .biz, etc.)";
            bSettings.AddSetting(TargetDomain);

            SettingItemSpecial TimeoutDelay     =   new SettingItemSpecial(AStr.TimeoutDelay,new IntegerDataType());
            TimeoutDelay.Required               =   true;
            TimeoutDelay.ResourceFile           =   AStr.ResourceFile;
            TimeoutDelay.ResourceItem           =   AStr.ResourceItem;
            TimeoutDelay.Value                  =   "300";
            TimeoutDelay.MinValue               =   60;
            TimeoutDelay.MaxValue               =   1200;
            TimeoutDelay.Order                  =   44;
            TimeoutDelay.ExtendedGroupName      =   extgrp;
            TimeoutDelay.EnglishName            =   "Timeout delay (s)";
            TimeoutDelay.Description            =   "This the maximum delay observed when sending bulk mails, will necessitate a loop to end the process";
            bSettings.AddSetting(TimeoutDelay);

            SettingItemSpecial SendMails        =   new SettingItemSpecial(AStr.SendMails,new BooleanDataType());
            SendMails.Required                  =   true;
            SendMails.ResourceFile              =   AStr.ResourceFile;
            SendMails.ResourceItem              =   AStr.ResourceItem;
            SendMails.Value                     =   StStr.strTrue;
            SendMails.Order                     =   47;
            SendMails.ExtendedGroupName         =   extgrp;
            SendMails.EnglishName               =   "Send emails";
            SendMails.Description               =   "When checked emails are sent, else just prepared";
            bSettings.AddSetting(SendMails);

            SettingItemSpecial ImgHandlerName   =   new SettingItemSpecial(AStr.ImgHandlerName,new StringDataType());
            ImgHandlerName.Required             =   true;
            ImgHandlerName.ResourceFile         =   AStr.ResourceFile;
            ImgHandlerName.ResourceItem         =   AStr.ResourceItem;
            ImgHandlerName.Value                =   "ImgHandler.ashx";
            ImgHandlerName.Order                =   48;
            ImgHandlerName.ExtendedGroupName    =   extgrp;
            ImgHandlerName.EnglishName          =   "Image handler for open mail url";
            ImgHandlerName.Description          =   "Name for the image handler user to detect mail opening, input a full path whith http if necessary";
            bSettings.AddSetting(ImgHandlerName);

            ArrayList ar    =   new ArrayList();
            string opt                          =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_OPEN_IMAGE","1px Image");
            ar.Add(new ListItem(opt,"Image"));
            opt                                 =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_OPEN_HTTPHANDLER","Http handler");
            ar.Add(new ListItem(opt,"handler"));

            SettingItemSpecial OpenHandlerType  =   new SettingItemSpecial(AStr.OpenHandlerType,new CustomListDataType(ar,"Text","Value"));
            OpenHandlerType.Required            =   false;
            OpenHandlerType.ResourceFile        =   AStr.ResourceFile;
            OpenHandlerType.ResourceItem        =   AStr.ResourceItem;
            OpenHandlerType.Value               =   "handler";
            OpenHandlerType.Order               =   50;
            OpenHandlerType.ExtendedGroupName   =   extgrp;
            OpenHandlerType.EnglishName         =   "Open mail tracking type";
            OpenHandlerType.Description         =   "To use the 'Image' type, you must have parametered IIS in accordance with documentation";
            bSettings.AddSetting(OpenHandlerType);

            SettingItemSpecial MaxErrors        =   new SettingItemSpecial(AStr.MaxErrors,new IntegerDataType());
            MaxErrors.Required                  =   true;
            MaxErrors.ResourceFile              =   AStr.ResourceFile;
            MaxErrors.ResourceItem              =   AStr.ResourceItem;
            MaxErrors.Value                     =   "500";
            MaxErrors.Order                     =   60;
            MaxErrors.ExtendedGroupName         =   extgrp;
            MaxErrors.EnglishName               =   "Max Errors";
            MaxErrors.Description               =   "Maximum number of errors before stopping";
            bSettings.AddSetting(MaxErrors);

            SettingItemSpecial PageSize         =   new SettingItemSpecial(AStr.PageSize,new IntegerDataType());
            PageSize.Required                   =   true;
            PageSize.ResourceFile               =   AStr.ResourceFile;
            PageSize.ResourceItem               =   AStr.ResourceItem;
            PageSize.Value                      =   "500";
            PageSize.Order                      =   70;
            PageSize.ExtendedGroupName          =   extgrp;
            PageSize.EnglishName                =   "Query max Page Size";
            PageSize.Description                =   "Maximum number of records in retrieve query";
            bSettings.AddSetting(PageSize);

            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2SI InitSettings END.",CrmBulkSendTrace.Sw.Info);
        }
 
        /// <summary>
        /// Used to set the good display value in Campaign when loaded from DB
        /// </summary>
        void Campaign_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2BaseSI Campaign_SettingItemsEvent Guid: {0}", e.Data),CrmBulkSendTrace.Sw.Info);
            Guid custId                     =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynCampaign dynac            =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defCampaign      =   (WSListDataType )((SettingItem)sender).DataType;
            defCampaign.DisplayTextValue    =   dynac.name;
            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2BaseSI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),CrmBulkSendTrace.Sw.Info);
        }

        /// <summary>
        /// Used to set the good display value in ModuleOwner when loaded from DB
        /// </summary>
        void ModuleOwner_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2SI ModuleOwner_SettingItemsEvent Guid: {0}", e.Data),CrmBulkSendTrace.Sw.Info);
            Guid custId     =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynSystemUser dynac  =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defAcc   =   (WSListDataType )((SettingItem)sender).DataType;
            defAcc.DisplayTextValue =   dynac.fullname;
            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2SI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),CrmBulkSendTrace.Sw.Info);
        }
    }

    /// <summary>
    ///	Dedicated input (only) module for leads
    /// </summary>
    public partial class CrmBSM2 : BulkSendModule
    {

        #region General implementation
        
        public override Guid GuidID
        {
            get
            {
                return new Guid(AStr.CrmBSM2Guid);
            }
        }
        
        #endregion General implementation

        public CrmBSM2()
        {
            if ( CrmBulkSendTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2 Ctor Called.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmBulkSendTrace.Sw.Info);
            ValidationGroup                         =   "Main";
        }

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer                 =   new CrmBSM2SI(bSettings,this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if ( CrmBulkSendTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 Page_Load  BEG IsPostBack: {0}, IsInAsyncPostBack: {1}.",IsPostBack,IsInAsyncPostBack),
                    (ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmBulkSendTrace.Sw.Info);
            ModuleProgressArea                      =   RadProgressArea1;
            // init localization string in progress manager/area
            InitProgress(); // Pb no persist between postback
            // Init MaxErrors
            MaxErrors                               =   Settings[AStr.MaxErrors].ToInt();
            // To have postback on finish for better delay
            const string fmt                        =   "realPostBack('{0}', ''); return false;";
            FinishBtn.OnClientClick                 =   string.Format(fmt, FinishBtn.UniqueID);

            if (!IsPostBack)
            {
                // Fill languages : Get it from Crm ?
                string str                          =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_ENGLISH","English");
                RadComboBoxItem it                  =   new RadComboBoxItem(str,"1033");
                CbLanguage.Items.Add(it);
                str                                 =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_FRENCH","French");
                it                                  =   new RadComboBoxItem(str,"1036");
                CbLanguage.Items.Add(it);
                // Default Target Page to welcome Page
                PagesList.IncludeDefaultWelcome     =   true;
                PagesList.SelectedTreeViewValue     =   StStr.PageIDNotAssigned.ToString();
                PagesList.DataBind();

                // Bind ActivityType
                ArrayList ar                        =   Wrapper.Util.ListFromPickList(CrmStr.typecode,CrmStr.campaignactivity);
                CbActivityType.DataTextField        =   StStr.smName;
                CbActivityType.DataValueField       =   StStr.smVal;
                CbActivityType.DataSource           =   ar;
                CbActivityType.DataBind();
                if ( CrmBulkSendTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( "[V]CrmBSM2 Page_Load  typecode Ok.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmBulkSendTrace.Sw.Info);
                //Bind priorities
                ar                                  =   Wrapper.Util.ListFromPickList(CrmStr.prioritycode,CrmStr.email);
                CbPriority.DataTextField            =   StStr.smName;
                CbPriority.DataValueField           =   StStr.smVal;
                CbPriority.DataSource               =   ar;
                CbPriority.DataBind();

                // Fill the campaign combo
                Guid CampaignId                     =    Settings[AStr.BulkCampaign].ToGuid();
                if ( CrmBulkSendTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 Page_Load  CampaignId: {0}.",CampaignId),CrmBulkSendTrace.Sw.Info);
                if ( CampaignId != Guid.Empty )
                {
                    ADNDynCampaign dnc              =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,ResetWrapper,CampaignId);
                    if ( dnc != null )
                    {
                        it                          =    new RadComboBoxItem(dnc.name,CampaignId.ToString());
                        it.Selected                 =   true;
                        CbCampaign.Items.Add(it);
                        CbCampaign.DataBind();
                        if (CrmBulkSendTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 Page_Load Campaign: {0}.",dnc.name),CrmBulkSendTrace.Sw.Info);
                    }
                }

                if ( Settings[AStr.FixedCampaign].ToBool() )
                    CbCampaign.Enabled  =   false;
                if ( CrmBulkSendTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 Page_Load Count: {0}.",CbCampaign.Items.Count),CrmBulkSendTrace.Sw.Info);
            }
            if ( CrmBulkSendTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2 Page_Load  END.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmBulkSendTrace.Sw.Info);
        }

        public override void SetMessage(string txt)
        {
            lbMsg.Visible   =   true;
            lbMsg.Text      =   txt;
        }

        protected override int GetLangCode()
        {
            return int.Parse(CbLanguage.SelectedValue);
        }

        void cbForExternal_CheckedChanged(object sender,EventArgs e)
        {
            string attr             =   string.Empty;
            TbClickUrl.Text         =   MakeTargetUrl(int.Parse(PagesList.SelectedTreeViewValue),attr,cbForExternal.Checked);
        }

        void PagesList_SelectedIndexChanged(object o,RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 PagesList_SelectedIndexChanged BEG e.value: {0}.",e.Value),CrmBulkSendTrace.Sw.Info);
            string url              =   string.Empty;
            try
            {
                string attr         =   string.Empty;
                url                 =   MakeTargetUrl(int.Parse(e.Value),attr,cbForExternal.Checked);
            }
            catch (Exception ex)
            {
                if (CrmBulkSendTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmBSM2 PagesList_SelectedIndexChanged  ex: {0}", ex),CrmBulkSendTrace.Sw.Info);
                throw;
            }
            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 PagesList_SelectedIndexChanged END url: {0}.",url),CrmBulkSendTrace.Sw.Info);
            TbClickUrl.Text         =   url;
        }
        
        void CbCampaign_SelectedIndexChanged(object o,RadComboBoxSelectedIndexChangedEventArgs e)
        {
            MarketingLists.DataSource   =   null;
            MarketingLists.Rebind();
        }

        void CbLanguage_SelectedIndexChanged(object o,RadComboBoxSelectedIndexChangedEventArgs e)
        {
            MarketingLists.DataSource   =   null;
            MarketingLists.Rebind();
        }

        void MarketingLists_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 MarketingLists_NeedDataSource BEG RebindReason: {0}.",e.RebindReason),CrmBulkSendTrace.Sw.Info);
            DataTable Tb                                =   null;
             MarketingLists.DataSource                  =   null;
            if ( RdBtnMarketing.Checked )
            {
                if ( string.IsNullOrEmpty(CbCampaign.SelectedValue) )
                    return;
                Guid CampaignId                         =    new Guid(CbCampaign.SelectedValue);
                if ( CrmBulkSendTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 MarketingLists_NeedDataSource  CampaignId: {0}.",CampaignId),CrmBulkSendTrace.Sw.Info);
                if ( CampaignId != Guid.Empty )
                {
                    ADNDynCampaign dynCamp              =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,ResetWrapper,CampaignId);
                    Tb                                  =   dynCamp.ReadAllListTb(ResetWrapper,string.Empty);
                    //Tb.Columns.Add("membercount",typeof(int));
                    Tb.Columns.Add("membersent",typeof(int));
                    foreach ( DataRow rw in Tb.Rows )
                    {
                        rw["membersent"]                =   0;
                    }
                }
            }
            else //if ( RdBtnDownloadSession.Checked )
            {
                if ( string.IsNullOrEmpty(CbDownloadSession.SelectedValue) )
                    return;
                Guid SessionIdId                        =    new Guid(CbDownloadSession.SelectedValue);
                if ( CrmBulkSendTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 MarketingLists_NeedDataSource  SessionIdId: {0}.",SessionIdId),CrmBulkSendTrace.Sw.Info);
                if ( SessionIdId != Guid.Empty )
                {
                    ADNDynDownloadSession dynSession    =   DynEntity.GetFromCache<ADNDynDownloadSession>(AStr.adndownloadsession,Wrapper,ResetWrapper,SessionIdId);
                    Tb                                  =   dynSession.ReadAllListsTb(ResetWrapper,string.Empty);
                    Tb.Columns.Add("membersent",typeof(int));
                    foreach ( DataRow rw in Tb.Rows )
                    {
                        rw["membersent"]                =   0;
                    }
                }

                if ( CrmBulkSendTrace.Sw.TraceVerbose )
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 MarketingLists_NeedDataSource Count: {0}.",( Tb != null ) ? Tb.Rows.Count : 0),CrmBulkSendTrace.Sw.Info);
                MarketingLists.DataSource               =   Tb;
            }
        }


        /// <summary>
        /// When downloadsession checked we must invalidate the marketing list cb
        /// and vice versa
        /// </summary>
       void RdBtnDownloadSession_CheckedChanged(object sender,EventArgs e)
        {
            bool enableMarketing        =   false;
            if ( sender == RdBtnDownloadSession )
            {
                if ( RdBtnDownloadSession.Checked )
                    enableMarketing     =   false;
                else enableMarketing    =   true;
            }
            else
            {
                if ( RdBtnMarketing.Checked )
                    enableMarketing     =   true;
                else enableMarketing    =   false;
            }
            CbCampaign.Enabled          = enableMarketing;
            CbDownloadSession.Enabled   = enableMarketing;
        }
        
        
        void BtnNext_Click(object sender,ImageClickEventArgs e)
        {
            int idx                         =   RadTabStrip1.SelectedIndex;
            if (CrmBulkSendTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 BtnNext_Click  BEG TabIndex: {0}.",idx),CrmBulkSendTrace.Sw.Info);
			RadTab Tab                      =   RadTabStrip1.Tabs[idx+1];
            RadPageView PageView            =   RadMultiPage1.PageViews[idx+1];
            bool ok                         =   true;
            switch (Tab.Index)
            {
                case 1:
                        if ( RdBtnMarketing.Checked && string.IsNullOrEmpty(CbCampaign.SelectedValue) )
                        {
                            string msg              =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_NOCAMPAIGN","You must select a campaign");
                            lbMsg1.Text              =   msg;
                            ok                      =   false;
                        }
            
                        else if ( RdBtnDownloadSession.Checked && string.IsNullOrEmpty(CbDownloadSession.SelectedValue) )
                        {
                            string msg              =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_NOSESSION","You must select a downloadsession");
                            lbMsg1.Text              =   msg;
                            ok                      =   false;
                        }
                       break;
                case 2:
                    break;
                case 6:
                    // allow update or reset
                    LabelSummary.Text       =   LocalizeHelper.Localize("CRM2CRM_LASTSUMMARY","Process summary");
                    updateBtn.Visible       =   true;
                    break;
            }
            if ( ok )
            {
		        Tab.Enabled                 =   true;
		        Tab.Selected                =   true;
                PageView.Selected           =   true;
            }

            if (CrmBulkSendTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 BtnNext_Click  END Tab.Index: {0}, ok: {1}, updateBtn.Visible: {2}.",Tab.Index,ok,updateBtn.Visible),CrmBulkSendTrace.Sw.Info);
		}

        /// <summary>
        /// Create all the mails
        /// </summary>
        void CrmBSM2_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2 CrmBSM2_ADNUpdateModule BEG.",CrmBulkSendTrace.Sw.Info);
           
            if ( RdBtnMarketing.Checked && string.IsNullOrEmpty(CbCampaign.SelectedValue) )
            {
                string msg              =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_NOCAMPAIGN","You must select a campaign");
                lbMsg.Text              =   msg;
                lbMsg.Visible           =   true;
                return;
            }
            
           if ( RdBtnDownloadSession.Checked && string.IsNullOrEmpty(CbDownloadSession.SelectedValue) )
            {
                string msg              =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_NOSESSION","You must select a downloadsession");
                lbMsg.Text              =   msg;
                lbMsg.Visible           =   true;
                return;
            }
            if ( string.IsNullOrEmpty(mailOwner.internalemailaddress) )
            {
                string msg              =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_NOSENDERMAIL","Sender has no email address");
                lbMsg.Text              =   msg;
                lbMsg.Visible           =   true;
                return;
            }
            if ( string.IsNullOrEmpty(PagesList.SelectedValue) )
            {
                string msg              =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_NOTARGETPAGE","You must select a target page");
                lbMsg.Text              =   msg;
                lbMsg.Visible           =   true;
                return;
            }
            List<GridDataItem> GriItems =   new List<GridDataItem>();
            for(int i=0; i < MarketingLists.Items.Count; i++)
            {
                GridItem it             =   MarketingLists.Items[i];
                if ( !(it is GridDataItem) )
                    continue;
                GridDataItem item       =   it as GridDataItem;
                RadComboBox CbTemplate  =   ((RadComboBox)item.FindControl("CbTemplate"));
                if ( CbTemplate == null )
                    continue;
                // keep only selected
                if ( CbSelected.Checked && !item.Selected )
                    continue;
                GriItems.Add(item);
            }
            if ( GriItems.Count == 0 )
            {
                string msg                                  =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_NOLIST","No list in this campaign");
                lbMsg.Text                                  =   msg;
                lbMsg.Visible                               =   true;
                return;
            }
            // Reset values in ViewState
            LstActivities                                   =   null;
            LstJobs                                         =   null;
            // Reset Err count
            ErrCount                                        =   0;
            bool BulkSend                                   =   true;
            try
            {
                int TargetPage                              =   int.Parse(PagesList.SelectedValue);
                bool OneActivity                            =   CbOneActivity.Checked;
                int excludeifcontactedinxdays               =   (TbExcludeIfContacted.Value.HasValue) ? (int)TbExcludeIfContacted.Value.Value:0;
                int prioritycode                            =   int.Parse(CbPriority.SelectedValue);
                if ( CrmBulkSendTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule TargetPage: {0}, Count: {1}, OneActivity: {2}, excludeifcontactedinxdays: {3}, prioritycode: {4}.",
                        new object[]{TargetPage,GriItems.Count,OneActivity,excludeifcontactedinxdays,prioritycode}),CrmBulkSendTrace.Sw.Info);
                Guid CampaignId                             =   Guid.Empty;
                Guid SessionId                              =   Guid.Empty;
                Guid ListId                                 =   Guid.Empty;
                ADNDynCampaign dynCamp                      =   null;
                if ( RdBtnMarketing.Checked )
                {
                    CampaignId                              =   new Guid(CbCampaign.SelectedValue);
                    dynCamp                                 =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,ResetWrapper,CampaignId);
                    if ( CrmBulkSendTrace.Sw.TraceVerbose )
                        Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule CampaignId: {0}.",CampaignId),CrmBulkSendTrace.Sw.Info);
                }
                else
                {
                    SessionId                               =   new Guid(CbDownloadSession.SelectedValue);
                    ADNDynDownloadSession dynSession        =   DynEntity.GetFromCache<ADNDynDownloadSession>(AStr.adndownloadsession,Wrapper,ResetWrapper,SessionId);
                    CampaignId                              =   dynSession.campaignid;
                    BulkSend                                =   ( CampaignId != Guid.Empty);
                    ListId                                  =   dynSession.listid;
                    if ( CrmBulkSendTrace.Sw.TraceVerbose )
                        Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule CampaignId: {0}, ListId: {1}.",CampaignId,ListId),CrmBulkSendTrace.Sw.Info);
                    if (( CampaignId == Guid.Empty ) && ( ListId == Guid.Empty ) )
                    {
                        lbMsg.Text                          =   "You must select a DownloadSession with a marketing campaign or a marketing list associated";
                        return;
                    }
                    string title                            =   dynSession.adntitle;
                    string prefix                           =   dynSession.adnprefix;
                    if (PrivateDocFeederTrace.Sw.TraceVerbose)
                        Trace2.WriteLine(  string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder FillWithCampaign title: {0}, prefix: {1}.",title,prefix),PrivateDocFeederTrace.Sw.Info);
                }
                string fmt                                  =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_ACTIVITYFMT","Mass mailing for {0}");
                ADNDynCampaignActivity dynAct               =   null;

                ProgressPrimaryTotal                        =   GriItems.Count;
                ProgressTotalSteps                          =   0;
                StartProgress();                
                for( int i=0; i < GriItems.Count; i++ )
                {
                    GridDataItem item                       =   GriItems[i];
                    Guid listid                             =   new Guid(MarketingLists.MasterTableView.DataKeyValues[item.ItemIndex]["listid"].ToString());
                    RadComboBox CbTemplate                  =   ((RadComboBox)item.FindControl("CbTemplate"));
                    if ( CrmBulkSendTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]CrmBSM2 CrmBSM2_ADNUpdateModule found CbTemplate.",CrmBulkSendTrace.Sw.Info);
                    ADNDynList dynList                      =   DynEntity.GetFromCache<ADNDynList>(CrmStr.list,Wrapper,ResetWrapper,listid);
                    if ( CrmBulkSendTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule dynList.listid: {0}, dynList.membercount: {1}.",dynList.listid,dynList.membercount),CrmBulkSendTrace.Sw.Info);
                    if ( dynList.membercount == 0 )
                        dynList.membercount                 =   dynList.GetMembers(ResetWrapper).Count;
                    ResetProgressSecTotal(dynList.membercount);
                    if ( CrmBulkSendTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule start listname: {0}, count: {1}.",dynList.listname,dynList.membercount),CrmBulkSendTrace.Sw.Info);
                    // Create new campaign activity
                    if ( BulkSend )
                    {
                        dynAct                              =   new ADNDynCampaignActivity(Wrapper,dynList.listname);
                        dynAct.DefaultRegardingObjectName   =   CrmStr.campaign;
                        dynAct.regardingobjectid            =   CampaignId;
                        dynAct.typecode                     =   int.Parse(CbActivityType.SelectedValue);
                        dynAct.channeltypecode              =   (int)ADNDynCampaignActivity.ChannelTypes.Email;
                        dynAct.excludeifcontactedinxdays    =   excludeifcontactedinxdays;
                        dynAct.Create();
                        LstActivities.Add(dynAct.activityid);
                        if ( CrmBulkSendTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule new campaignactivity: {0}.",dynAct.activityid),CrmBulkSendTrace.Sw.Info);
                    }
                    // Add list to the activity items
                    if ( dynAct != null )
                        dynAct.AddItem(dynList,false);                    
                    Guid TemplateID                         =   new Guid(CbTemplate.SelectedValue);
                    ADNDynTemplate dynTemp                  =   DynEntity.GetFromCache<ADNDynTemplate>(CrmStr.template,Wrapper,ResetWrapper,TemplateID);
                    if ( CrmBulkSendTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule template: [{0}].",dynTemp.title),CrmBulkSendTrace.Sw.Info);
                    // Should we Bulk it
                    if ( BulkSend )
                    {
                        bool propagate                      =   true;
                        bool sendmail                       =   false;
                        ADNDynEmail dynMail                 =   new ADNDynEmail(Wrapper,dynTemp.subject);
                        dynMail.prioritycode                =   prioritycode;
                        Guid JobId                          =   dynAct.DistributeCampaignActivity(dynMail,dynTemp,propagate,false,sendmail,mailOwner,false);
                        LstJobs.Add(JobId);
                        if ( CrmBulkSendTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule JobId: [{0}].",JobId),CrmBulkSendTrace.Sw.Info);
                        continue;
                    }
                    
                    List<ADNDynCustomer> MissMail           =   new List<ADNDynCustomer>();
                    dynList.ExecForEachMember(ResetWrapper,delegate(ADNDynCustomer dynCust)
                    {
                        if ( CrmBulkSendTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule starting listMember: {0}, emailaddress1: '{1}'.",
                                dynCust.PrimaryFieldStringValue,dynCust.emailaddress1),CrmBulkSendTrace.Sw.Info);
                        // must have a mail address
                        if ( string.IsNullOrEmpty(dynCust.emailaddress1) )
                        {
                            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( "[V]CrmBSM2 CrmBSM2_ADNUpdateModule Excluded no email.",CrmBulkSendTrace.Sw.Info);
                            MissMail.Add(dynCust);
                            string fmt1                     =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_SKIP","Skip {0}");
                            string msg                      =   string.Format(fmt1,dynCust.PrimaryFieldStringValue);
                            ProgressSecCount                +=  1;
                            SetUpdateProgress(msg,ProgressPrimCount,ProgressSecCount);
                            return true;
                        }
                        DateTime lastused                   =   dynCust.lastusedincampaignLocalDate;
                        DateTime ExcludeDate                =   lastused.AddDays((double)excludeifcontactedinxdays);
                        if (  ExcludeDate > DateTime.Now )
                        {
                            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule Excluded Date: {0}.",
                                    ExcludeDate),CrmBulkSendTrace.Sw.Info);
                            MissMail.Add(dynCust);
                            string fmt1                     =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_SKIP","Skip {0}");
                            string msg                      =   string.Format(fmt1,dynCust.PrimaryFieldStringValue);
                            ProgressSecCount                +=  1;
                            SetUpdateProgress(msg,ProgressPrimCount,ProgressSecCount);
                            return true;
                        }
                        string fmt2                         =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_MAILTO","Mailing to {0}");
                        string msg2                         =   string.Format(fmt2,dynCust.PrimaryFieldStringValue);
                        ProgressSecCount                    +=  1;
                        SetUpdateProgress(msg2,ProgressPrimCount,ProgressSecCount);

                        ADNDynEmail mail                    =   Wrapper.Util.InstantiateTemplate(dynTemp,dynCust,false);
                        mail.prioritycode                   =   prioritycode;
                        if ( CrmBulkSendTrace.Sw.TraceVerbose )
                        {
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule mail.description: [{0}].",mail.description),CrmBulkSendTrace.Sw.Info);
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule mail.subject: [{0}].",mail.subject),CrmBulkSendTrace.Sw.Info);
                        }
                        // complete actual mail with sender, dest and regarding
                        mail.AddDest(dynCust);
                        mail.AddSender(mailOwner);
                        mail.DefaultRegardingObjectName     =   CrmStr.campaignactivity;
                        if ( dynAct != null )
                            mail.regardingobjectid          =   dynAct.activityid;
                        mail.ownerid                        =   mailOwner.systemuserid;
                        try
                        {
                        string newSubject                   =   UpdateMailContent(SessionId,mail,dynList.MemberTypename,dynCust,CampaignId,TargetPage,true,CbUnsubscribe.Checked,TbUnsubscribe.Text.Trim(),cbMailOpen.Checked,TbClickUrl.Text.Trim());
                        }
                        catch // we stop process
                        {
                            return false;
                        }
                        fmt2                                =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_SENTTO","Mail sent to {0}");
                        msg2                                =   string.Format(fmt2,dynCust.PrimaryFieldStringValue);
                        SetUpdateProgress(msg2,ProgressPrimCount,ProgressSecCount);
                        return true;
                    });
                    if (( MaxErrors > 0 ) && ( ErrCount >= MaxErrors ) )
                    {
                        if ( CrmBulkSendTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule END maxErrors reached: {0}.",MaxErrors),CrmBulkSendTrace.Sw.Info);
                        return;
                    }
                if ( CrmBulkSendTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 CrmBSM2_ADNUpdateModule end listname: [{0}].",dynList.listname),CrmBulkSendTrace.Sw.Info);
                }
            }
            catch (Exception ex)
            {
                if (CrmBulkSendTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmBSM2 CrmBSM2_ADNUpdateModule  ex: {0}", ex),CrmBulkSendTrace.Sw.Info);
                throw;
            }
            finally
            {
                // Force save in viewstate
                if ( _LstActivities != null && ( _LstActivities.Count > 0 ) )
                    LstActivities                       =   _LstActivities;
                if ( _LstJobs != null && ( _LstJobs.Count > 0 ) )
                    LstJobs                             =   _LstJobs;
                EndProgress();
                // No error we display refresh button
                if ( ( ( MaxErrors ==0 ) || ( ErrCount < MaxErrors) ) && BulkSend )
                    refreshBtn.Visible                  =   true;
                updateBtn.Enabled                       =   false;
            }
            if ( CrmBulkSendTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2 CrmBSM2_ADNUpdateModule END.",CrmBulkSendTrace.Sw.Info);
        }

        void refreshBtn_Click(object sender,EventArgs e)
        {
			if (CrmBulkSendTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 refreshBtn_Click BEG LstJobs.Count: {0}",LstJobs.Count),CrmBulkSendTrace.Sw.Info);
            FinishBtn.Visible           =   false;
            foreach ( Guid jobId in LstJobs )
            {
                ADNDynBulkoperation dynBulk             =   DynEntity.GetFromCache<ADNDynBulkoperation>(CrmStr.bulkoperation,Wrapper,ResetWrapper,jobId);
                if ( !dynBulk.Wait4BulkCompletion(true,20) )
                {
                    lbMsg.Text          =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_BATCHPENDING","Emails generation running");
			        if (CrmBulkSendTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 refreshBtn_Click not completed Bulk.subject: {0}",dynBulk.subject),CrmBulkSendTrace.Sw.Info);
                    return; //not finished
                }
            }
	        if (CrmBulkSendTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmBSM2 refreshBtn_Click END completed.",CrmBulkSendTrace.Sw.Info);
            FinishBtn.Visible           =   true;
            //Finished
            lbMsg.Text                  =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_BATCHCOMPLETE","Emails generation completed");
        }
        

        void  FinishBtn_Click(object sender, EventArgs e)
        {
			if (CrmBulkSendTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click BEG LstActivities.Count: {0}",LstActivities.Count),CrmBulkSendTrace.Sw.Info);
            ProgressPrimaryTotal                                    =   LstActivities.Count;
            ProgressTotalSteps                                      =   0;
            StartProgress();                
            int TargetPage                                          =   int.Parse(PagesList.SelectedValue);
            Guid CampaignId                                         =   new Guid(CbCampaign.SelectedValue);
            // Reset Err count
            ErrCount                                                =   0;
            int TotalCount                                          =   0;
            DateTime dstart                                         =   DateTime.Now;
            DateTime dmax                                           =   dstart.AddSeconds((double)Settings[AStr.TimeoutDelay].ToInt());
			if (CrmBulkSendTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click Start: {0:s}, End : {1:s}",dstart,dmax),CrmBulkSendTrace.Sw.Info);
            bool totalSent                                          =   true;
            try
            {
                // Query for all mail activities created
                foreach( Guid ActId in LstActivities)
                {
                    SortedList<Guid,ADNDynList> LstLst              =   null;
                    string key                                      =   string.Format("BULK_{0}",ActId);
                    if ( !AddonNice.Settings.Cache.CurrentCache.Exists(key) )
                    {
                        ADNDynCampaignActivity dynAct               =   DynEntity.GetFromCache<ADNDynCampaignActivity>(CrmStr.campaignactivity,Wrapper,ResetWrapper,ActId);
			            if (CrmBulkSendTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click dynAct.subject: {0}",dynAct.subject),CrmBulkSendTrace.Sw.Info);
                        LstLst                                      =   dynAct.ReadAllList(ResetWrapper,string.Empty);
                        if ( LstLst.Count != 0 )
                             AddonNice.Settings.Cache.CurrentCache.InsertLong(key,LstLst);
                    }
                    else
                    {
                        LstLst                                      =  (SortedList<Guid,ADNDynList>)  AddonNice.Settings.Cache.CurrentCache.Get(key);
                    }
			        if (CrmBulkSendTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click ReadAllList Count: {0}",LstLst.Count),CrmBulkSendTrace.Sw.Info);
                    if ( LstLst.Count == 0 )
                    {
                        continue;
                    }
                    DateTime dNow                                   =   DateTime.Now;
                    long ticks                                      =   (dNow.Ticks-dstart.Ticks)/TimeSpan.TicksPerSecond;
			        if (CrmBulkSendTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click After List retrieve now: {0:s}, Elapsed : {1} s",dNow,ticks),CrmBulkSendTrace.Sw.Info);
                    ADNDynList dynList                              =   LstLst.Values[0];
			        if (CrmBulkSendTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click dynList.listname: {0}",dynList.listname),CrmBulkSendTrace.Sw.Info);
                    GenericDynQueryMultiple<ADNDynEmail> allEntQuery=   new GenericDynQueryMultiple<ADNDynEmail>(Wrapper,ResetWrapper,CrmStr.email);
                    bool paging                                     =   false;
                    int PageSize                                    =   Settings[AStr.PageSize].ToInt();
                    if ( dynList.membercount > PageSize )
                    {
                        paging                                      =   true;
                        allEntQuery.PageSize                        =   PageSize;
                        allEntQuery.PageNumber                      =   1;
                        allEntQuery.UsePaging                       =   true;
			            if (CrmBulkSendTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click Paging listname: {0}, Count: {1}",dynList.listname,dynList.membercount),CrmBulkSendTrace.Sw.Info);
                    }
                    string fmt2                                     =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_LOADINGFMT","Loading mails for {0} list members");
                    int loadsz                                      =   (PageSize > dynList.membercount ) ? dynList.membercount:PageSize;
                    string msg2                                     =   string.Format(fmt2,loadsz);
                    SetUpdateProgress(msg2,ProgressPrimCount,ProgressSecCount);
                    
                    string keyMail                                  =   string.Format("BULK_MAILS_{0}",ActId);
                    SortedList<Guid,ADNDynEmail> LstMails           =   null;
                    if ( paging || !AddonNice.Settings.Cache.CurrentCache.Exists(keyMail) )
                    {
                        InternalColumnSet colset                    =   new InternalColumnSet();
                        colset.Attributes                           =   new string[]{CrmStr.activityid,CrmStr.statuscode,CrmStr.statecode};

                        InternalConditionExpression eMailCondition  =   new InternalConditionExpression();
                        eMailCondition.AttributeName                =   CrmStr.regardingobjectid;
                        eMailCondition.Operator                     =   InternalConditionOperator.Equal;
                        eMailCondition.Values                       =   new object[] {ActId};

                        InternalConditionExpression eMailCondition2 =   new InternalConditionExpression();
                        eMailCondition2.AttributeName               =   CrmStr.statecode;
                        eMailCondition2.Operator                    =   InternalConditionOperator.Equal;
                        eMailCondition2.Values                      =   new object[] {CrmStr.StateActive};

                        InternalConditionExpression eMailCondition3 =   new InternalConditionExpression();
                        eMailCondition3.AttributeName               =   CrmStr.statuscode;
                        eMailCondition3.Operator                    =   InternalConditionOperator.NotIn;
                        eMailCondition3.Values                      =   new object[] {(int)ADNDynEmail.EmailStatus.Canceled,
                                                                                            (int)ADNDynEmail.EmailStatus.Sending,
                                                                                            (int)ADNDynEmail.EmailStatus.Sent,
                                                                                            (int)ADNDynEmail.EmailStatus.Failed,
                                                                                            (int)ADNDynEmail.EmailStatus.PendingSend};

                        InternalFilterExpression regardingObjectFi  =   new InternalFilterExpression();
                        regardingObjectFi.Conditions                =   new InternalConditionExpression[] { eMailCondition,eMailCondition2,eMailCondition3 };
                        regardingObjectFi.FilterOperator            =   InternalLogicalOperator.And;
                        
                        InternalQueryExpression eMailQuery          =   new InternalQueryExpression();
                        eMailQuery.ColumnSet                        =   colset;
                        eMailQuery.Criteria                         =   regardingObjectFi;
                        eMailQuery.EntityName                       =   CrmStr.email;

                        LstMails                                    =   allEntQuery.retrieveSortedList(eMailQuery);
                         if ( LstMails.Count != 0 )
                             AddonNice.Settings.Cache.CurrentCache.InsertLong(keyMail,LstMails);
                    }
                    else
                    {
                        LstMails                                    =   (SortedList<Guid,ADNDynEmail>)  AddonNice.Settings.Cache.CurrentCache.Get(keyMail);
                    }
                    dNow                                            =   DateTime.Now;
                    ticks                                           =   (dNow.Ticks-dstart.Ticks)/TimeSpan.TicksPerSecond;
			        if (CrmBulkSendTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click After Mails retrieve now: {0:s}, Elapsed : {1} s",dNow,ticks),CrmBulkSendTrace.Sw.Info);
                   
                    do
                    {
			            if (CrmBulkSendTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click LstMails.Count: {0}",LstMails.Count),CrmBulkSendTrace.Sw.Info);
                        ResetProgressSecTotal(LstMails.Count);
                        int cnt                                     =   0;
                        long maxticks                               =   0;
                        foreach(ADNDynEmail mail in LstMails.Values)
                        {
                            TotalCount++;
                            cnt++;
			                if (CrmBulkSendTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click count: {0}, activityid: {1}, statecode: {2}, statuscode: {3}",
                                    new object[]{cnt,mail.activityid,mail.statecode,mail.statuscode}),CrmBulkSendTrace.Sw.Info);
                            // To get all attributes
                            mail.Retrieve();
                            // filter already sent mails
                            switch ((ADNDynEmail.EmailStatus)mail.statuscode)
                            {
                                case ADNDynEmail.EmailStatus.Canceled:
                                case ADNDynEmail.EmailStatus.Sending:
                                case ADNDynEmail.EmailStatus.Sent:
                                case ADNDynEmail.EmailStatus.Failed:
                                case ADNDynEmail.EmailStatus.PendingSend:
                                continue;
                            }
                            mail.ResetCache(true);
                            string txt1                             =   string.Format("{0}/{1} {2}",cnt,LstMails.Count,mail.subject);
                            fmt2                                    =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_MAILSUBJECT","Mail subject: {0}");
                            msg2                                    =   string.Format(fmt2,txt1);
                            ProgressSecCount                        +=  1;
                            SetUpdateProgress(msg2,ProgressPrimCount,ProgressSecCount);
                            DynEntity dynCust                       =   mail.ExtractTo(true,true)[0];
                            try
                            {
                                dNow                                =   DateTime.Now;
                                DateTime dtemp                      =   dNow;
                                ticks                               =   (dNow.Ticks-dstart.Ticks)/TimeSpan.TicksPerSecond;
			                    if (CrmBulkSendTrace.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click Mails: {0}/{1} now: {2:s}, Elapsed : {3} s",
                                        new object[]{cnt,LstMails.Count,dNow,ticks}),CrmBulkSendTrace.Sw.Info);
                                string newSubject                   =   UpdateMailContent(Guid.Empty,mail,dynList.MemberTypename,dynCust,CampaignId,TargetPage,false,CbUnsubscribe.Checked,TbUnsubscribe.Text.Trim(),cbMailOpen.Checked,TbClickUrl.Text.Trim());
                                dNow                                =   DateTime.Now;
                                long ticks2                         =   (dNow.Ticks-dtemp.Ticks)/TimeSpan.TicksPerSecond;
                                maxticks                            =   (ticks2 > maxticks) ? ticks2:maxticks;
			                    if (CrmBulkSendTrace.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click After sending: {0}/{1} now: {2:s}, length : {3} s, maxlength: {4} s",
                                        new object[]{cnt,LstMails.Count,dNow,ticks2,maxticks}),CrmBulkSendTrace.Sw.Info);
                                if ( CrmBulkSendTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click sent mail: {0}, Subject: {1}.",mail.activityid,newSubject),CrmBulkSendTrace.Sw.Info);
                            }
                            catch
                            { 
                                if (( MaxErrors > 0 ) && ( ErrCount >= MaxErrors ) )
                                {
                                    if ( CrmBulkSendTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click END maxErrors reached: {0}.",MaxErrors),CrmBulkSendTrace.Sw.Info);
                                    totalSent                           =   false;
                                    throw;
                                }
                            }
                            dNow                                        =   DateTime.Now;
                            ticks                                       =   (dNow.Ticks-dstart.Ticks)/TimeSpan.TicksPerSecond;
                            if ( dNow.AddSeconds(maxticks) > dmax )
                            {
                                totalSent                               =   false;
                                break;
                            }
                        }
		                if (CrmBulkSendTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click Paging Next records paging: {0}, MoreRecords: {1}",paging,allEntQuery.MoreRecords),CrmBulkSendTrace.Sw.Info);
                        if ( dNow.AddSeconds(maxticks) > dmax )
                        {
                            string fmt                                  =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"BULK_STILLTOSEND","There are {0} emails left to send, press the send button again");        
                            lbMsg.Text                                  =   string.Format(fmt,LstMails.Count-cnt);
                            break;
                        }
                        if ( paging && allEntQuery.MoreRecords )
                        {
			                if (CrmBulkSendTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click Paging Next PagingCookie: {0}",allEntQuery.PagingCookie),CrmBulkSendTrace.Sw.Info);
                            fmt2                                        =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_LOADINGFMT","Loading mails for {0} list members");
                            loadsz                                      =   (PageSize > dynList.membercount ) ? dynList.membercount:PageSize;
                            msg2                                        =   string.Format(fmt2,loadsz);
                            SetUpdateProgress(msg2,ProgressPrimCount,ProgressSecCount);
                            LstMails                                    =   allEntQuery.retrieveNextSortedList();
			                if (CrmBulkSendTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click Paging After Count: {0}, PagingCookie: {1}",LstMails.Count,allEntQuery.PagingCookie),CrmBulkSendTrace.Sw.Info);
                            if ( LstMails.Count == 0 )
                                break;
                        }
                    } while( paging);

                }
                if ( totalSent )
                {
                    lbMsg.Text                                          =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"BULK_ALLMAILSSENT","All emails have been sent");        
                }
            }
            catch(Exception ex)
            { 
                if ( CrmBulkSendTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmBSM2 FinishBtn_Click END ex: {0}.",ex),CrmBulkSendTrace.Sw.Info);
                string msg                      =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TEMPLATE_TIMEOUT","Timeout, press Finish until final sending");
                lbMsg.Text                      =   msg;
                // try avoiding further processing of this errror
                Server.ClearError();
                return;
            }
            finally
            { 
                 EndProgress();
            }
	        if (CrmBulkSendTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmBSM2 FinishBtn_Click END completed : {0}.",totalSent),CrmBulkSendTrace.Sw.Info);
        }

        #region Std overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
            if ( CrmBulkSendTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2 Page_PreInit BEG.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmBulkSendTrace.Sw.Info);
            base.Page_PreInit(sender, e);
            string strcult      =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            BtnNext0.SkinID     =   "setupnext_" + strcult;
            BtnNext1.SkinID     =   "setupnext_" + strcult;
            BtnNext2.SkinID     =   "setupnext_" + strcult;
            BtnNext3.SkinID     =   "setupnext_" + strcult;
            updateBtn.SkinID    =   "Update_" + strcult;
            if ( CrmBulkSendTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2 Page_PreInit  END.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmBulkSendTrace.Sw.Info);
        }


        override protected void OnInit(EventArgs e)
        {
            if ( CrmBulkSendTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2 OnInit BEG.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmBulkSendTrace.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
            if ( CrmBulkSendTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmBSM2 OnInit  END.",(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmBulkSendTrace.Sw.Info);
        }

        private void InitializeComponent()
        {
            Load                                        +=  new System.EventHandler(Page_Load);
            CbDownloadSession.WebServiceSettings.Method =   "GetDownloadSessions";
            CbDownloadSession.WebServiceSettings.Path   =   "/Services/XrmEmailing.asmx";

            CbDownloadSession.WebServiceMethod          =   "GetDownloadSessions";
            CbDownloadSession.WebServicePath            =   "/Services/XrmEmailing.asmx";
            
            ADNUpdateModule                             +=  new PortalModuleEventHandler(CrmBSM2_ADNUpdateModule);
            CbCampaign.AutoPostBack                     =   true;
            CbCampaign.SelectedIndexChanged             +=  new RadComboBoxSelectedIndexChangedEventHandler(CbCampaign_SelectedIndexChanged);
            CbLanguage.AutoPostBack                     =   true;
            CbLanguage.SelectedIndexChanged             +=  new RadComboBoxSelectedIndexChangedEventHandler(CbLanguage_SelectedIndexChanged);
            MarketingLists.ItemDataBound                +=  new GridItemEventHandler(MarketingLists_ItemDataBound);
            MarketingLists.NeedDataSource               +=  new GridNeedDataSourceEventHandler(MarketingLists_NeedDataSource);
            refreshBtn.Click                            +=  new EventHandler(refreshBtn_Click);
            FinishBtn.Click                             +=  new EventHandler(FinishBtn_Click);
            PagesList.IncludeAdmin                      =   false;
            PagesList.AutoPostBack                      =   true;
            PagesList.SelectedIndexChanged              +=  new RadComboBoxSelectedIndexChangedEventHandler(PagesList_SelectedIndexChanged);
            cbForExternal.AutoPostBack                  =   true;
            cbForExternal.CheckedChanged                +=  new EventHandler(cbForExternal_CheckedChanged);

            RdBtnDownloadSession.AutoPostBack           =   true;
            RdBtnDownloadSession.CheckedChanged         +=  new EventHandler(RdBtnDownloadSession_CheckedChanged);
            RdBtnMarketing.AutoPostBack                 =   true;
            RdBtnMarketing.CheckedChanged               +=  new EventHandler(RdBtnDownloadSession_CheckedChanged);

            BtnNext0.Click                              +=  new ImageClickEventHandler(BtnNext_Click);
            BtnNext1.Click                              +=  new ImageClickEventHandler(BtnNext_Click);
            BtnNext2.Click                              +=  new ImageClickEventHandler(BtnNext_Click);
            BtnNext3.Click                              +=  new ImageClickEventHandler(BtnNext_Click);
        }



        #endregion Std overrides
    }
}